<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '数据库测试',
  },
}
</route>
<template>
  <view class="database-test-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="flex items-center">
        <text class="i-fa-solid:chevron-left text-lg mr-2" @click="goBack"></text>
        <text class="text-xl font-semibold">数据库测试</text>
      </view>
    </view>

    <!-- 测试内容 -->
    <scroll-view scroll-y class="p-4 test-container">
      <!-- 测试状态 -->
      <view v-if="loading" class="mb-4 p-4 bg-gray-100 rounded-lg">
        <text class="text-gray-500">{{ loadingMessage }}</text>
      </view>

      <!-- 测试操作 -->
      <view class="mb-4">
        <view class="text-lg font-semibold mb-2">数据库操作</view>
        
        <view class="flex flex-col space-y-2">
          <button class="test-button" @click="initDatabase">初始化数据库</button>
          <button class="test-button" @click="createTestTask">创建测试任务</button>
          <button class="test-button" @click="fetchAllTasks">获取所有任务</button>
          <button class="test-button" @click="updateTestTask" :disabled="!currentTask">更新当前任务</button>
          <button class="test-button bg-red-500" @click="deleteTestTask" :disabled="!currentTask">删除当前任务</button>
        </view>
      </view>

      <!-- 当前任务 -->
      <view v-if="currentTask" class="mb-4">
        <view class="text-lg font-semibold mb-2">当前任务</view>
        <view class="bg-white p-4 rounded-lg shadow-sm">
          <view class="mb-2">
            <text class="font-medium">ID：</text>
            <text>{{ currentTask.id }}</text>
          </view>
          <view class="mb-2">
            <text class="font-medium">标题：</text>
            <text>{{ currentTask.title }}</text>
          </view>
          <view class="mb-2">
            <text class="font-medium">优先级：</text>
            <text>{{ currentTask.priority }}</text>
          </view>
          <view class="mb-2">
            <text class="font-medium">状态：</text>
            <text>{{ currentTask.completed ? '已完成' : '未完成' }}</text>
          </view>
          <view class="mb-2">
            <text class="font-medium">创建时间：</text>
            <text>{{ formatDate(currentTask.createdAt) }}</text>
          </view>
        </view>
      </view>

      <!-- 任务列表 -->
      <view class="mb-4">
        <view class="text-lg font-semibold mb-2">任务列表 ({{ tasks.length }})</view>
        <view v-if="tasks.length === 0" class="bg-gray-100 p-4 rounded-lg">
          <text class="text-gray-500">暂无任务</text>
        </view>
        <view v-else class="bg-white rounded-lg shadow-sm">
          <view
            v-for="task in tasks"
            :key="task.id"
            class="p-4 border-b border-gray-100 last:border-0"
            @click="selectTask(task)"
          >
            <view class="flex justify-between items-center">
              <text :class="{ 'line-through': task.completed }">{{ task.title }}</text>
              <view
                :class="[
                  'priority-dot',
                  {
                    'bg-red-500': task.priority === 'high',
                    'bg-orange-500': task.priority === 'medium',
                    'bg-green-500': task.priority === 'low',
                  },
                ]"
              ></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 测试结果 -->
      <view class="mb-4">
        <view class="text-lg font-semibold mb-2">测试日志</view>
        <view class="bg-gray-100 p-4 rounded-lg">
          <text class="whitespace-pre-wrap">{{ logs }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { dbService } from '@/services/database'
import { taskService, type Task } from '@/services/task-service'

defineOptions({
  name: 'DatabaseTestPage',
})

// 获取屏幕安全区域
const { safeAreaInsets } = uni.getSystemInfoSync()

// 状态
const loading = ref(false)
const loadingMessage = ref('')
const tasks = ref<Task[]>([])
const currentTask = ref<Task | null>(null)
const logs = ref('')

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 添加日志
const addLog = (message: string) => {
  logs.value = `${formatTime(new Date())}: ${message}\n${logs.value}`
  console.log(message)
}

// 格式化时间
const formatTime = (date: Date) => {
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${formatTime(date)}`
}

// 初始化数据库
const initDatabase = async () => {
  loading.value = true
  loadingMessage.value = '正在初始化数据库...'
  
  try {
    const result = await dbService.init()
    addLog(`数据库初始化${result ? '成功' : '失败'}`)
  } catch (error) {
    addLog(`数据库初始化出错: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

// 创建测试任务
const createTestTask = async () => {
  loading.value = true
  loadingMessage.value = '正在创建测试任务...'
  
  try {
    const taskId = await taskService.createTask({
      title: `测试任务 ${new Date().toLocaleTimeString()}`,
      priority: ['high', 'medium', 'low'][Math.floor(Math.random() * 3)] as 'high' | 'medium' | 'low',
      category: '测试',
      description: '这是一个测试任务',
    })
    
    addLog(`创建任务成功，ID: ${taskId}`)
    await fetchAllTasks()
    
    // 获取并设置当前任务
    const task = await taskService.getTaskById(taskId)
    if (task) {
      currentTask.value = task
      addLog(`已设置当前任务: ${task.title}`)
    }
  } catch (error) {
    addLog(`创建任务出错: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

// 获取所有任务
const fetchAllTasks = async () => {
  loading.value = true
  loadingMessage.value = '正在获取任务列表...'
  
  try {
    // 获取未完成任务
    const incompleteTasks = await taskService.getIncompleteTasks()
    // 获取已完成任务
    const completedTasks = await taskService.getCompletedTasks()
    
    // 合并任务列表
    tasks.value = [...incompleteTasks, ...completedTasks]
    
    addLog(`获取任务成功，共 ${tasks.value.length} 条任务 (${incompleteTasks.length} 未完成, ${completedTasks.length} 已完成)`)
  } catch (error) {
    addLog(`获取任务列表出错: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

// 更新测试任务
const updateTestTask = async () => {
  if (!currentTask.value) {
    addLog('没有选择任务，无法更新')
    return
  }
  
  loading.value = true
  loadingMessage.value = '正在更新任务...'
  
  try {
    const task = currentTask.value
    const newTitle = `更新的任务 ${new Date().toLocaleTimeString()}`
    
    // 更新任务
    const success = await taskService.updateTask(task.id, {
      title: newTitle,
      description: `${task.description || ''} (已更新)`,
    })
    
    addLog(`更新任务${success ? '成功' : '失败'}`)
    
    if (success) {
      // 重新获取任务
      const updatedTask = await taskService.getTaskById(task.id)
      if (updatedTask) {
        currentTask.value = updatedTask
        addLog(`更新后的任务标题: ${updatedTask.title}`)
      }
      
      // 刷新任务列表
      await fetchAllTasks()
    }
  } catch (error) {
    addLog(`更新任务出错: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

// 删除测试任务
const deleteTestTask = async () => {
  if (!currentTask.value) {
    addLog('没有选择任务，无法删除')
    return
  }
  
  loading.value = true
  loadingMessage.value = '正在删除任务...'
  
  try {
    const task = currentTask.value
    
    // 删除任务
    const success = await taskService.deleteTask(task.id)
    
    addLog(`删除任务${success ? '成功' : '失败'}`)
    
    if (success) {
      currentTask.value = null
      // 刷新任务列表
      await fetchAllTasks()
    }
  } catch (error) {
    addLog(`删除任务出错: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

// 选择任务
const selectTask = (task: Task) => {
  currentTask.value = task
  addLog(`已选择任务: ${task.title}`)
}

// 页面加载时初始化数据库
onMounted(async () => {
  addLog('页面加载完成')
  await initDatabase()
  await fetchAllTasks()
})
</script>

<style lang="scss" scoped>
.database-test-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.test-container {
  height: calc(100vh - 88px - var(--status-bar-height));
}

.test-button {
  background-color: #3498db;
  color: white;
  padding: 12px;
  border-radius: 8px;
  font-weight: 500;
  
  &:disabled {
    opacity: 0.5;
  }
}

.priority-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}
</style> 